/*
 * 文件名：PassFinController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：wuzhiyang
 * 修改时间：2020年1月12日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.cap.web;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import top.infopub.mgr.cap.domain.PassFinAssist;
import top.infopub.mgr.cap.domain.PassFinDomain;
import top.infopub.mgr.cap.service.PassFinService;
import top.infopub.mgr.cap.service.SetupFinService;
import top.infopub.mgr.cap.vo.PassFinVo;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.sg.service.CoopInfoService;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.cap.PassFinAtt;
import top.infopub.model.cap.SetupFin;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.sg.CoopInfo;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import com.github.pagehelper.Page;


/**
 * 审批通过
 * @author wuzhiyang
 * @version 2020年1月12日
 * @see PassFinController
 * @since
 */
@Controller
@RequestMapping("/passFin")
public class PassFinController extends GenericFlowController {

    @Autowired
    private PassFinService passFinService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private SetupFinService setupFinService;

    @Autowired
    private CoopInfoService coopInfoService;

    /**
     * 融资立项列表
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "cap/lay-passFin-list";
    }

    /**
     * 融资立项列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<PassFinDomain> queryDataByCondition(PassFinVo passFinVo, ParamPage paramPage) {
        Page<PassFinDomain> page = new Page<PassFinDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (passFinVo.getEndDate() != null) {
            passFinVo.setEndDate(DateUtils.addDays(passFinVo.getEndDate(), 1));
        }
        //增加addby
        passFinVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = passFinService.selectByDomainWhere(page, passFinVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 融资立项列表数据
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<PassFinDomain> queryMyCheckDataByCondition(PassFinVo passFinVo,
                                                            ParamPage paramPage) {
        Page<PassFinDomain> page = new Page<PassFinDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (passFinVo.getEndDate() != null) {
            passFinVo.setEndDate(DateUtils.addDays(passFinVo.getEndDate(), 1));
        }
        //增加addby
        passFinVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = passFinService.selectMyCheckByDomainWhere(page, passFinVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 审批通过-新增
     * @return
     */
    @RequestMapping("/add")
    public String toAdd(HttpServletRequest request) {
        String bindOrgId = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgId"));
        String bindOrgName = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgName"));
        String bindDeptId = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptId"));
        String bindDeptName = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptName"));
        request.setAttribute("bindOrgId", bindOrgId);
        request.setAttribute("bindOrgName", bindOrgName);
        request.setAttribute("bindDeptId", bindDeptId);
        request.setAttribute("bindDeptName", bindDeptName);
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        //返回所有融资立项中的项目名称
        List<SetupFin> list = setupFinService.selectAll(null, null);
        request.setAttribute("allProName", list);
        //返回所有承贷企业的单位名称
        List<CoopInfo> coopCode = coopInfoService.selectByCoopCode(null);
        request.setAttribute("coopInfoName", coopCode);
        return "cap/lay-passFin-add";
    }

    /**
     * 通过项目id和单据id查询记录(带出融资立项信息)
     */
    @RequestMapping("/getSetupFinByProCode")
    @ResponseBody
    public Map<String, Object> getSetupFinByProCode(HttpServletRequest request) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String proCode = "";
            String codes = "";
            String proCodeAndCodes = request.getParameter("proCodeAndCodes");
            String[] strCodes = proCodeAndCodes.split("\\_");
            proCode = strCodes[0];
            codes = strCodes[1];
            SetupFin setupFin = new SetupFin();
            setupFin.setProCode(proCode);
            setupFin.setId(codes);
            List<SetupFin> setupFinList = setupFinService.selectByEntityWhere(setupFin);
            if (setupFinList.size() == 1) {
                map.put("setupFinList", setupFinList.get(0));
            }
            //返回所有承贷企业的单位名称
            List<CoopInfo> coopCode = coopInfoService.selectByCoopCode(null);
            map.put("coopAll", coopCode);
        }
        catch (Exception e) {
            log.error("根据项目ID获取融资立项信息异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 融资审批-新增
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/save")
    @ResponseBody
    public RspVo save(PassFinAssist passFinAssist) {

        //主表-审批通过
        passFinAssist.setRequires(passFinAssist.getRequire());
        passFinAssist.setCapSchemeMemo(passFinAssist.getCapSchemeMemos());
        passFinAssist.setHrDeptId(passFinAssist.getHrDeptid());
        passFinAssist.setHrOrgId(passFinAssist.getHrOrgid());
        passFinAssist.setStaffName(passFinAssist.getStaffname());
        passFinAssist.setHrStaffApplyId(passFinAssist.getHrStaffApplyid());
        String proCode = "";
        String setupFinId = "";
        String[] strCodes = passFinAssist.getProCodeAndCodes().split("\\_");
        proCode = strCodes[0];
        setupFinId = strCodes[1];
        passFinAssist.setProCode(proCode);
        SetupFin setup = new SetupFin();
        setup.setProCode(proCode);
        setup.setId(setupFinId);
        List<SetupFin> list = setupFinService.selectByEntityWhere(setup);
        //添加项目名称
        for (SetupFin setupFin : list) {
//            passFinAssist.setProName(setupFin.getProName());
            //添加城市调研信息ID
//            passFinAssist.setSgCityId(setupFin.getSgCityId());
            //添加融资立项id
            passFinAssist.setSetupFinId(setupFin.getId());
        }
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String id = IdFactory.getUUIDUpper();
        passFinAssist.setId(id);
        passFinAssist.setAddBy(vo.getId());
        passFinAssist.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String codes = codeGeneratorConfigService.generatorCode("cap_pass_fin");
        passFinAssist.setCodes(codes);
        // 处理processId
        passFinAssist.setProcessId(IdFactory.getUUIDUpper());
        passFinAssist.setProcessStatus("1");//审批中
        passFinAssist.setTypes("1");//PPP项目
        passFinAssist.setUptBy(vo.getId());
        passFinAssist.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        //上传附件
        List<PassFinAtt> passFinAtts = new ArrayList<PassFinAtt>();
        String[] fileAtts = passFinAssist.getFileAtts();
        if (fileAtts != null) {
            for (String file : fileAtts) {
                PassFinAtt passFinAtt = createFileAtt(vo, id, file);
                passFinAtts.add(passFinAtt);
            }
        }
        passFinService.savePassFin(passFinAssist, passFinAtts);
        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD,
            "融资管理 -新增审批通过：项目名=" + passFinAssist.getProName(), null);
        return RspVo.getSuccessResponse();
    }

    private PassFinAtt createFileAtt(AuthorizationVO vo, String passFinId, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        PassFinAtt fileAtt = new PassFinAtt();
        fileAtt.setId(IdFactory.getUUIDUpper());
        fileAtt.setPassFinId(passFinId);//项目id
        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
            fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 上传附件
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    @ResponseBody
    public RspVo updateAtt(HttpServletRequest request) {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
        if (fileMap != null) {
            for (String name : fileMap.keySet()) {
                MultipartFile file = fileMap.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                //上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                //服务器资源路径
                String serverPath = "passFinAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add("|" + file.getOriginalFilename().trim() + "|" + fileId + "|"
                                      + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传审批通过附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

    /**
     * 根据id查询审批通过详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 审批通过Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request, String id, String processDealWith) {
        Map<String, Object> map = new HashMap<String, Object>();
        PassFinVo passFinVo = passFinService.selectById(id);
        request.setAttribute("modelDetail", passFinVo);
        map.put("passFinVo", passFinVo);
        // 审批flag
        request.setAttribute("processDealWith", processDealWith);
        // 审批data
        processData(request, passFinVo.getProcessId());
        return new ModelAndView("cap/lay-passFin-detail", map);
    }

    /**
     * 融资审批-复制单据
     * @return
     */
    @RequestMapping("/toCopy")
    public String toCopy(HttpServletRequest request, String id) {
        PassFinVo passFinVo = passFinService.selectById(id);
        request.setAttribute("passFinVo", passFinVo);
        //返回所有承贷企业的单位名称
        List<CoopInfo> coopCode = coopInfoService.selectByCoopCode(null);
        request.setAttribute("coopInfoName", coopCode);
        return "cap/lay-passFin-copy";
    }

}
